package com.administration.managedBean;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
import javax.servlet.http.Cookie;

import com.administration.controller.AdministrationController;
import com.administration.entity.Groups;
import com.administration.entity.User;
import com.common.Mail;
import com.common.Utility;
import com.core.managedBean.BaseBean;
import com.entity.RegisteredUser;

/*
 * @author KarimSherif
 */
@ManagedBean
@ViewScoped
public class UserBean extends BaseBean {
	private static final long serialVersionUID = 1L;
	private String userName;
	private String password;
	private String email;
	private User user = new User();
	private Boolean rememberMe = Boolean.FALSE;
	private List<User> userList;
	List<Groups> groupsList;
	private SelectItem[] groupFilter;
	private AdministrationController administrationController;;

	// \\###############################################################################

	@PostConstruct
	public void loadData() {
		if (administrationController == null) {
			administrationController = new AdministrationController();
		}
		loadAllGroups();
		loadAllUsers();
		loadGroupsNameForFilter();
//		loadUserDetailes();
		loadLoggedUserInformation();
	}

	public void checkbpreviousLogin() {
		String uName = isLoggedInBefore();
		if (uName != null) {
			try {
				User user = administrationController.getUser(uName);
				this.userName = user.getUserName();
				this.password = user.getPassword();
				RegisteredUser registeredUser = administrationController
						.loginUser(this.userName, this.password);
				super.setSessionAttribute("registeredUser", registeredUser);
				// "HTTP:"+super.getRequest().getServerName()+":"+super.getRequest().getServerPort()+"/"+
				super.getResonse().sendRedirect(
						super.getRequest().getContextPath()
								+ "/controlling/index.xhtml");
			} catch (Exception e) {
				e.printStackTrace();
				super.addErrorMessage("Please Check your internet/database connection");
			}

		}
	}

	public String loginUser() {
		try {
			RegisteredUser registeredUser = administrationController.loginUser(
					this.userName, Utility.PasswordEncrypt(this.password));
			if (registeredUser != null) {
				super.setSessionAttribute("registeredUser", registeredUser);
				if (rememberMe) {
					Cookie cookie = new Cookie("userName", userName);
					cookie.setMaxAge(60 * 60 * 24 * 30);// means 1 month
					String cookiePath = super.getRequest().getContextPath()
							+ "/controlling/";
					cookie.setPath(cookiePath);
					super.getResonse().addCookie(cookie);
				}
				return "success";
			} else {
				super.addErrorMessage("User Name/Password Incorrect or you are in an Inactive Group");
				
			}
		} catch (Exception ex) {
			super.addErrorMessage("User Name/Password Incorrect or you are in an Inactive Group");
			ex.printStackTrace();
		}
		return null;
	}

	public String logOut() {
		com.common.Utility.terminateSession();
		return "logOut";
	}

	public void saveUser() {
		try {
			if (this.user.getUserId() == null) {
				Long userId = administrationController.addUser(user);
				this.user.setUserId(userId);
			} else {
				administrationController.updateUser(user);
			}
			super.addInfoMessage("successfully Saved user "
					+ user.getFirstName() + " " + user.getSecondName());
		} catch (Exception ex) {
			ex.printStackTrace();
			super.addErrorMessage("Please Check your internet/database connection");
		}
	}

	public void deleteUser() {
		try {
			administrationController.deleteUser(this.user);
			loadAllUsers();
		} catch (Exception e) {
			e.printStackTrace();
			super.addErrorMessage("Please Check your internet/database connection");
		}
	}

	public void forgetPassword() {
		try {
			User user = administrationController.getUserByEmail(email);
			Mail m = new Mail();
			m.setTo(user.getEmail());
			m.setSubject("Your Password");
			m.setContent("Your Password is  "
					+ Utility.PasswordEncrypt(user.getPassword()));
			m.sendEmail();
			super.addInfoMessage("An email send to your mail contains the password");
		} catch (Exception e) {
			e.printStackTrace();
			super.addErrorMessage("An Error Occured");
		}

	}

	public String isLoggedInBefore() {
		Cookie[] cookies = super.getRequest().getCookies();
		if (cookies == null || cookies.length < 1) {
			return null;
		}
		String cookieName = null;
		String uname = null;
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			cookieName = cookie.getName();
			if (cookieName.equals("userName")) {
				uname = cookie.getValue();
				break;
			}

		}
		cookies = null;
		cookieName = null;
		return uname;

	}

	public void loadLoggedUserInformation() {
		try {
			RegisteredUser registeredUser = (RegisteredUser) super
					.getSessionAttribute("registeredUser");
			if (registeredUser != null) {
				User dbUser;
				dbUser = administrationController.getUserById(registeredUser
						.getUserId());
				this.user = dbUser;
			}
		} catch (Exception e) {
			e.printStackTrace();
			super.addErrorMessage("Please Check your internet/database connection");
		}
	}

	public void getListUserByGroupId() {
		try {
			this.userList = administrationController.getListUserByGroupId(user
					.getGroupId());
		} catch (Exception e) {
			e.printStackTrace();
			super.addErrorMessage("Please Check your internet/database connection");
		}
	}

	public void loadAllUsers() {
		try {
			this.userList = administrationController.getAllUsers();
		} catch (Exception e) {
			super.addErrorMessage("Please Check your internet/database connection");
			e.printStackTrace();
		}
	}

	public void loadUserDetailes() {
		Object usereObject = super.getFlashAttribute("user");
		if (usereObject != null) {
			user = (User) usereObject;
		}
	}

	public void loadAllGroups() {
		try {
			groupsList = administrationController.getAllGroups();
		} catch (Exception ex) {
			super.addErrorMessage("please check your network/internet connection");
			ex.printStackTrace();
		}

	}

	public void loadGroupsNameForFilter() {
		if (this.userList != null) {
			this.setGroupFilter(createFilterOptions());
		}
	}

	private SelectItem[] createFilterOptions() {
		SelectItem[] options = null;
		try {
			List<Groups> gl = administrationController.getAllGroups();
			options = new SelectItem[gl.size() + 1];
			options[0] = new SelectItem("", "Select");
			for (int i = 0; i < gl.size(); i++) {
				options[i + 1] = new SelectItem(gl.get(i).getRecid(), gl.get(
						i).getName());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return options;
	}

	public String tologin() {
		return "login";
	}

	public String toCreateUser() {
		return "toCreateUser";
	}

	public String toEditUser() {
		super.setFlashAttribute("user", user);
		return "toEditUser";
	}

	public String toUserIndex() {
		return "toUserIndex";
	}

	// \\############################################################################################################

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Boolean getRememberMe() {
		return rememberMe;
	}

	public void setRememberMe(Boolean rememberMe) {
		this.rememberMe = rememberMe;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getEmail() {
		return email;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	public List<User> getUserList() {
		return userList;
	}

	public List<Groups> getGroupsList() {
		return groupsList;
	}

	public void setGroupsList(List<Groups> groupsList) {
		this.groupsList = groupsList;
	}

	private void setGroupFilter(SelectItem[] filterOptions) {
		this.groupFilter = filterOptions;
	}

	public SelectItem[] getGroupFilter() {
		return groupFilter;
	}

}
